import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/Login.vue';
import Register from '../views/Register.vue';
import Home from '../views/Home.vue'; // 导入Home组件
import Store from '../views/StoreManage.vue';
import Consumer from '../views/Consumer.vue';
import Payment from '@/views/Payment.vue';
import OrderSuccess from '@/views/OrderSuccess.vue';
import Order from "@/views/Order.vue";
import OrderDetail from '@/views/OrderDetail.vue';
import OrderCancel from '@/views/OrderCancel.vue';
import { compact } from 'lodash';

// 路由守卫：检查是否有token
const requireAuth = (to, from, next) => {
  const token = localStorage.getItem('token');
  if (!token) {
    next('/login'); // 未登录则跳转到登录页
  } else {
    next(); // 已登录则继续
  }
};

// 已登录用户访问登录/注册页时跳转到主页
const redirectIfAuthenticated = (to, from, next) => {
  const token = localStorage.getItem('token');
  if (token) {
    next('/home'); // 已登录则跳转到主页
  } else {
    next(); // 未登录则继续
  }
};

const routes = [
  {
    path: '/',
    redirect: '/login' // 根路径默认重定向到登录页
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    beforeEnter: redirectIfAuthenticated
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    beforeEnter: redirectIfAuthenticated
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    beforeEnter: requireAuth // 访问主页需要验证
  },
  {
    path: '/storemanage',
    name: 'Store',
    component: Store,
  },
  {
  path: '/commodity/:storeId',
  name: 'Commodity',
  component: () => import('../views/Commodity.vue')
  },
  {
    path: '/consumer',
    name: 'Consumer',
    component: Consumer
  },
   {
    path: '/payment', // 注意：路径是 /payment，不是 /payment/:id
    name: 'Payment',
    component: Payment,
    props: (route) => ({ 
      orderId: route.query.orderId // 将查询参数 orderId 转为组件 props
    }),
    // 路由守卫：确保有订单ID才允许进入
    beforeEnter: (to, from, next) => {
      if (to.query.orderId) {
        next(); // 有订单ID，允许进入
      } else {
        next({ name: 'Consumer' }); // 无订单ID，跳回选购页面
      }
    }
  },
  {
    path: '/order/success',
    name: 'OrderSuccess',
    component: OrderSuccess
  },
  {
    path: '/order',
    name: 'Order',
    component: Order
  },
  {
    path: '/order/:id',
    name: 'OrderDetail',
    component: OrderDetail,
  },
  {
    path: '/order/:id/cancel',
    name: 'OrderCancel',
    component: OrderCancel
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;
    